package com.wangxiaonan.apiversion.common.configuration;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

/**
 * @Author: wangxiaonan
 * @Date: 2018/12/13
 **/
public class ApiVersionCondition implements RequestCondition<ApiVersionCondition> {

    // extract the version part from url. example [v0-9]
    private final static Pattern VERSION_PREFIX_PATTERN = Pattern.compile("v(\\d+)/");
    private int version;

    ApiVersionCondition(int version) {
        this.version = version;
    }

    @Override
    public ApiVersionCondition combine(ApiVersionCondition other) {
        return new ApiVersionCondition(other.getVersion());
    }

    @Override
    public ApiVersionCondition getMatchingCondition(HttpServletRequest request) {
        Matcher matcher = VERSION_PREFIX_PATTERN.matcher(request.getRequestURI());
        if (matcher.find()) {
            Integer version = new Integer(matcher.group(1));
            // when applying version number bigger than configuration, then it will take effect
            if (version >= this.version) {
                return this;
            }
        }
        return null;
    }

    @Override
    public int compareTo(ApiVersionCondition other, HttpServletRequest request) {
        return other.version - this.version;
    }

    public int getVersion() {
        return version;
    }
}
